<template lang="">
  <div>
    <div class="search">
      <el-form ref="form" :model="query" label-width="80px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="客户姓名">
              <el-input size="small" v-model="query.name"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="客户手机">
              <el-input size="small" v-model="query.phone"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="归属人">
              <el-input size="small" v-model="query.owner"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="6">
            <el-form-item label="渠道来源">
              <el-select
                size="small"
                v-model="query.channelId"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.channelName"
                  :value="item.channelId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="线索状态">
              <el-select
                size="small"
                v-model="query.status"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in statusOption"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item size="small" label="跟进时间">
              <el-date-picker
                v-model="value1"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>

          <el-button @click="reset">取消</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="btn" style="display: flex">
      <el-button type="primary" icon="el-icon-plus" plain @click="addshow"
        >新增</el-button
      >
      <el-button type="success" icon="el-icon-edit-outline" plain :disabled='delId.length != 1' @click='editshow(null)'
        >修改</el-button
      >
      <el-button type="danger" icon="el-icon-delete" plain :disabled='delId.length == 0' @click='deleteClue(null)'>删除</el-button>
      <el-button type="warning" icon="el-icon-plus" plain @click="exportXlsx"
        >导出</el-button
      >
    </div>

    <el-dialog :title=title :visible.sync="dialogVisible" width="50%">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="ruleForm.phone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="name">
              <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="渠道来源">
              <el-select
                size="small"
                v-model="ruleForm.channelId"
                placeholder="请选择"
                @change="channelChange"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.channelName"
                  :value="item.channelId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动信息">
              <el-select
                size="small"
                v-model="ruleForm.activityId"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in actOption"
                  :key="item.value"
                  :label="item.name"
                  :value="item.activityId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户性别">
              <el-radio-group v-model="ruleForm.gender">
                <el-radio
                  v-for="(item, index) in sex"
                  :key="index"
                  :label="item.value"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户年龄">
              <el-input-number
                size="small"
                v-model="ruleForm.age"
                :min="18"
                :max="100"
                label="年龄"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="微信号">
              <el-input v-model="ruleForm.weixin"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="QQ号">
              <el-input v-model="ruleForm.qq"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
          <el-button @click="resetForm('ruleForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <div class="table" style="margin-top: 20px">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>

        <el-table-column prop="clueId" label="线索编号" width="80">
        </el-table-column>

        <el-table-column prop="name" label="客户姓名" width="80">
        </el-table-column>

        <el-table-column prop="phone" label="手机号码"> </el-table-column>

        <el-table-column prop="channelName" label="渠道来源"> </el-table-column>

        <el-table-column
          prop="createTime"
          label="创建时间"
          width="180"
          show-overflow-tooltip
        >
        </el-table-column>

        <el-table-column prop="owner" label="线索归属"> </el-table-column>

        <el-table-column prop="status" label="线索状态">
          <template v-slot="scope">
            <!-- 当前行的信息 -->

            <!-- {{scope.row}} -->

            <el-tag v-if="scope.row.status == 1">已分配</el-tag>

            <el-tag v-if="scope.row.status == 2" type="success">跟进中</el-tag>

            <el-tag type="info" v-if="scope.row.status == 0">未知</el-tag>

            <el-tag type="warning" v-if="scope.row.status == 4">伪线索</el-tag>

            <el-tag type="danger" v-if="scope.row.status == 3">回收</el-tag>
          </template>
</el-table-column>
<el-table-column prop="nextTime" label="下次跟进时间" width="180">
</el-table-column>
<el-table-column label="操作" width="150">
  <template v-slot="scope">
            <el-button size="mini" @click='editshow(scope.row.clueId)'> 修改</el-button>
            <el-button
              type="danger"
              size="mini"
              @click.native="deleteClue(scope.row.clueId)"
              >删除</el-button
            >
          </template>
</el-table-column>
</el-table>
<!-- current-page当前页码 -->
<page :total="total" :page="query.pageNum" @size="setSize" @current="setCurrent"></page>
</div>
</div>
</template>
<script>
import page from "@/components/page.vue";
import { clueList, channels, clueStatus, activity, clueAdd, clueDel, summary, clueEidtor, exportClue } from "@/api/clue";
import { delt } from "@/api/delete";
export default {
  components: {
    page,
  },
  data() {
    var vaildatePhone = (rule, value, callback) => {
      const reg = /^1[3-9]\d{9}$/;
      if (value) {
        if (reg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的11位手机号'))
        }
      } else {
        callback(new Error('手机号不能为空'))
      }
    }
    return {
      dialogVisible: false,
      id: null,
      title: null,
      tableData: [],
      options: [],
      statusOption: [],
      actOption: [],
      value: "",
      value1: "",
      delId: [],
      query: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        phone: null,
        owner: null,
        channelId: null,
        status: null,
      },
      total: 0,
      sex: [
        {
          label: "男",
          value: 0,
        },
        {
          label: "女",
          value: 1,
        },
        {
          label: "未知",
          value: 2,
        },
      ],
      ruleForm: {
        name: "",
        phone: "",
        gender: 0,
        activityId: "",
        channelId: "",
        age: 1,
        weixin: "",
        qq: "",
      },
      rules: {
        name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
        phone: [{ required: true, validator: vaildatePhone, trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
    this.getchannels();
    this.getStatus();
  },
  methods: {
    //修改打开弹窗
    editshow(val) {
      //从表格当前行修改
      if (val) {
        this.delId[0] = val
      }
      this.dialogVisible = true
      this.title = '修改'
      summary(this.delId).then(async (res) => {
        this.ruleForm.name = res.data.name
        this.ruleForm.gender = res.data.gender
        this.ruleForm.phone = res.data.phone
        this.ruleForm.qq = res.data.qq
        this.ruleForm.weixin = res.data.weixin
        this.ruleForm.age = res.data.age
        if (res.data.channelId) {
          this.ruleForm.channelId = res.data.channelId
          //再次调用活动列表
          await this.channelChange(res.data.channelId)
          this.ruleForm.activityId = res.data.activityId
        }
      })
    },
    //删除
    deleteClue(val) {
      let id = val ? val : this.delId
      //数组的隐式转换
      this.$confirm(`此操作将永久删除编号为${id}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        clueDel(id).then(res => {
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
          .catch((err) => {
            this.$message({
              type: 'error',
              message: err.message
            });
          })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //渠道来源发送变化是触发
    channelChange(val) {
      this.ruleForm.activityId = null
      activity(val).then((res) => {
        this.actOption = res.data;
      });
    },
    addshow() {
      this.dialogVisible = true;
      this.title = '新增'
      //
      this.$nextTick(() => {
        //重置表单及校验
        this.$refs.ruleForm.resetFields();
      })
    },
    //重置
    reset() {
      this.query.pageNum = 1;
      this.query.pageSize = 10;
      this.query.channelId = null;
      this.query.name = null;
      this.query.owner = null;
      this.query.phone = null;
      this.query.status = null;
      this.getList();
    },
    //查询
    handleSearch() {
      //重置页面 从第一页查
      this.query.pageNum = 1;
      // this.setCurrent(1)
      this.getList();
    },
    // 线索状态
    async getStatus() {
      const res = await clueStatus();
      this.statusOption = res.data;
    },
    //线索列表
    getchannels() {
      channels().then((res) => {
        this.options = res.data;
      });
    },
    getList() {
      clueList(this.query).then((res) => {
        // console.log(res);
        this.tableData = res.rows;
        this.total = res.total;
      });
    },
    //多选
    handleSelectionChange(val) {
      this.delId = []
      for (const item of val) {
        this.delId.push(item.clueId)
      }
      console.log(this.delId)
    },
    setSize(val) {
      // console.log(`每页 ${val} 条`);
      this.query.pageSize = val;
      this.query.pageNum = 1;
      //重新调用接口
      this.getList();
    },
    setCurrent(val) {
      // console.log(`当前页: ${val}`);
      this.query.pageNum = val;
      //重新调用接口
      this.getList();
    },
    del(val) {
      delt(val).then((res) => {
        // console.log(res, '2111')
      });
      this.getList();
    },
    submitForm(formName) {
      //再进行一次校验
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title == '新增') {

            clueAdd(this.ruleForm).then(res => {
              //新增成功后
              if (res.code == 200) {
                this.$message({
                  message: '新增成功',
                  type: 'success'
                })
                //关闭模态框
                this.dialogVisible = false
                // 列表刷新
                this.getList()
                //重置表单和校验
                this.$refs[formName].resetFields();
              }
            })
              .catch(err => {
                this.$message({
                  message: err.msg,
                  type: 'error'
                })
              })
          } else {
            //参数
            let data = {
              clueId: this.delId[0],
              ...this.ruleForm
            }
            //修改
            clueEidtor(data).then(res => {
              this.$message.success('修改成功')
              this.dialogVisible = false
              this.getList()
            })
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });

    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible = false
      this.ruleForm.channelId = null
      this.ruleForm.activityId = null
    },
    //导出
    exportXlsx() {
      exportClue(this.query).then(res => {
        // console.log(res, '成功');
        // 创建一个blob对象 存储excel文件数据
        let blob = new Blob([res])
        const link = document.createElement('a')
        //创建一个下载链接  并将其赋值给href   
        link.href = window.URL.createObjectURL(blob)
        link.target = '_blank'
        //设置文件名
        let nowTime = new Date()
        link.setAttribute('download', `导出课程名字${nowTime.getTime()}.xlsx`)
        //将a标签添加到页面上
        document.body.appendChild(link)
        //触发点击事件
        link.click()
        //移出a标签
        document.body.removeChild(link)
      })
        .catch(err => {
          console.log(err);
        })
    }
  },
};
</script>
<style lang=""></style>
